import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:yuan_hang_app/base/base_page.dart';
import 'package:yuan_hang_app/res/w_colors.dart';
import 'package:yuan_hang_app/res/w_dimens.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/widget/w_text.dart';

import 'package:yuan_hang_app/widget/w_toast.dart';
import 'package:easy_refresh/easy_refresh.dart';

class WListView extends StatefulWidget {
  final Widget Function(BuildContext context, int index, List list) itemBuilder;
  Function(WListViewState currentState, int page)? getDataList;
  final int size;
  final Widget Function(BuildContext context, int index)? separatorBuilder;
  final EdgeInsetsGeometry padding;
  final ScrollPhysics? physics;

  WListView({
    super.key,
    required this.itemBuilder,
    this.getDataList,
    this.separatorBuilder,
    this.padding = EdgeInsets.zero,
    this.physics,
    this.size = 20,
  });

  @override
  WListViewState createState() => WListViewState();
}

class WListViewState extends State<WListView> {
  //当前列表的状态0--没有更多，1上拉加载更多
  int currentListStatus = 0;
  Status mStatus = Status.LOADING;
  List dataList = [];
  final ScrollController _scrollController = ScrollController();
  late EasyRefreshController _controller;
  int page = 1;
  String errorCode = '';

  void onRefreshData(List list, int mPage) {
    if (!mounted) return;
    page = mPage;
    return setState(() {
      if (page == 1) {
        dataList.clear();
        dataList.addAll(list);
      } else {
        dataList.addAll(list);
      }
      mStatus = dataList.isEmpty ? Status.EMPTY : Status.NONE;
      currentListStatus = list.length < widget.size ? 0 : 1;
    });
  }

  void onFail(e) {
    if (mounted) {
      setState(() {
        mStatus = Status.ERROR;
        errorCode = e;
      });
    }
  }

  void showRefresh() {
    if (!mounted) return;
    setState(() {
      mStatus = Status.LOADING;
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _controller = EasyRefreshController(
      controlFinishRefresh: true,
      controlFinishLoad: true,
    );
    widget.getDataList!(this, page);
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return LayoutBuilder(builder: (context, viewportConstraints) {
      return BasePage(
        hint: errorCode,
        status: mStatus,
        onTap: () {

          _refresh();
        },
        height: viewportConstraints.maxHeight,
        child: EasyRefresh(
            controller: _controller,
            canLoadAfterNoMore:false,
            canRefreshAfterNoMore: true,
            resetAfterRefresh: true,
            refreshOnStart: false,
            simultaneously: true,
            header: ClassicHeader(
              dragText: "下拉刷新",
              armedText: "松手刷新",
              messageText:
                  "最后一次更新${DateUtil.formatDate(DateTime.now(), format: DateFormats.h_m)}",
              messageStyle:
                  TextStyle(color: WColors.CCCCCCC, fontSize: WDimens.tsSmall),
              processedText: "刷新成功",
              readyText: '刷新中...',
              processingText: "刷新中...",
              succeededIcon: const SizedBox(),
              iconTheme: const IconThemeData(color: WColors.primaryColor),
              textStyle:
                  TextStyle(color: WColors.CCCCCCC, fontSize: WDimens.tsMedium),
            ),
            footer: ClassicFooter(
                noMoreText: "没有更多数据了",
                dragText: "上拉加载更多",
                processedText: "加载成功",
                readyText: '加载中...',
                processingText: "加载中...",
                messageText:
                    "最后一次更新${DateUtil.formatDate(DateTime.now(), format: DateFormats.h_m)}",
                messageStyle: TextStyle(
                    color: WColors.CCCCCCC, fontSize: WDimens.tsSmall),
                succeededIcon: const SizedBox(),
                noMoreIcon: const SizedBox(),
                iconTheme: const IconThemeData(color: WColors.primaryColor),
                textStyle: TextStyle(
                    color: WColors.CCCCCCC, fontSize: WDimens.tsMedium)),
            onRefresh: _refresh,
            onLoad:  currentListStatus == 0? null:_loadMore,
            child: SizedBox(
              height: viewportConstraints.maxHeight,
              child: ListView.separated(
                physics:
                    widget.physics ?? const AlwaysScrollableScrollPhysics(),
                shrinkWrap: true,
                controller: _scrollController,
                padding: widget.padding,
                itemBuilder: _itemBuilder,
                itemCount: dataList.length+1,
                separatorBuilder:
                    widget.separatorBuilder ?? (context, index) => Container(),
              ),
            )),
      );
    });
  }

  Future<Null> _refresh() async {
    if (!mounted) return;
    setState(() {
      page = 1;
      widget.getDataList!(this, page);
    });
    _controller.finishRefresh();
   // _controller.resetFooter();
  }

  Future<Null> _loadMore() async {
    if (!mounted) return;
    if(currentListStatus == 0){
      return;
    }
   // _controller.controlFinishLoad = currentListStatus == 0;
    page++;
    widget.getDataList!(this, page);
    _controller.finishLoad(currentListStatus == 1 ? IndicatorResult.success : IndicatorResult.noMore);
  }

  Widget _itemBuilder(context, index) {
    if(index==dataList.length){
      return more();
    }else{
      return widget.itemBuilder(context, index, dataList);
    }

  }

  Widget more() {
    return Container(
      alignment: Alignment.center,
      padding: EdgeInsets.all(10.px),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Padding(
            padding: EdgeInsets.only(right: 10.px),
            child: SizedBox(
                width: currentListStatus == 1 ? 20.px : 0,
                height: currentListStatus == 1 ? 20.px : 0,
                child: const CircularProgressIndicator(strokeWidth: 3)),
          ),
          WText(
            currentListStatus == 1 ? "上拉加载更多" : "没有更多数据了",
            style:
                TextStyle(color: WColors.CCCCCCC, fontSize: WDimens.tsMedium),
          )
        ],
      ),
    );
  }
}
